class DanmakuClient {
    constructor(container) {
        this.container = container;
        this.socket = null;
        this.roomId = null;
        this.tracks = [];
        this.initTracks();
    }

    initTracks() {
        const height = this.container.clientHeight;
        const trackHeight = height / 5;

        for (let i = 0; i < 5; i++) {
            this.tracks.push({
                top: i * trackHeight,
                inUse: false
            });
        }
    }

    connect(wsUrl, roomId) {
        if (this.socket) this.disconnect();

        this.roomId = roomId;
        this.socket = new WebSocket(`${wsUrl}?roomId=${roomId}`);

        this.socket.onopen = () => {
            console.log('WebSocket connected');
            document.getElementById('connect').disabled = true;
            document.getElementById('disconnect').disabled = false;
        };

        this.socket.onclose = () => {
            console.log('WebSocket disconnected');
            document.getElementById('connect').disabled = false;
            document.getElementById('disconnect').disabled = true;
        };

        this.socket.onmessage = (event) => {
            const danmaku = JSON.parse(event.data);
            this.displayDanmaku(danmaku);
        };

        this.socket.onerror = (error) => {
            console.error('WebSocket error:', error);
        };
    }

    disconnect() {
        if (this.socket) {
            this.socket.close();
            this.socket = null;
        }
    }

    sendDanmaku(content, user, style) {
        if (!this.socket || this.socket.readyState !== WebSocket.OPEN) {
            alert('请先连接到弹幕服务器');
            return;
        }

        if (!content || content.trim() === '') {
            alert('弹幕内容不能为空');
            return;
        }

        const message = {
            roomId: this.roomId,
            content,
            userId: user || 'anonymous',
            color: style?.color || '#ffffff',
            size: style?.size || 24
        };

        this.socket.send(JSON.stringify(message));
    }

    displayDanmaku(danmaku) {
        const danmakuElement = document.createElement('div');
        danmakuElement.className = 'danmaku';
        danmakuElement.textContent = danmaku.content;
        danmakuElement.style.color = danmaku.color || '#ffffff';
        danmakuElement.style.fontSize = `${danmaku.size || 24}px`;

        const track = this.findAvailableTrack();
        if (!track) return;

        danmakuElement.style.top = `${track.top}px`;
        this.container.appendChild(danmakuElement);

        const startX = this.container.clientWidth;
        const endX = -danmakuElement.clientWidth;
        let startTime = null;

        const animate = (timestamp) => {
            if (!startTime) startTime = timestamp;
            const progress = (timestamp - startTime) / 10000;

            if (progress < 1) {
                const x = startX + (endX - startX) * progress;
                danmakuElement.style.transform = `translateX(${x}px)`;
                requestAnimationFrame(animate);
            } else {
                this.container.removeChild(danmakuElement);
                track.inUse = false;
            }
        };

        track.inUse = true;
        requestAnimationFrame(animate);
    }

    findAvailableTrack() {
        return this.tracks.find(track => !track.inUse);
    }
}

// 初始化客户端
const container = document.getElementById('danmaku-container');
const client = new DanmakuClient(container);

// 绑定事件
document.getElementById('connect').addEventListener('click', () => {
    const roomId = document.getElementById('roomId').value;
    client.connect('ws://' + window.location.host + '/danmaku/ws/danmaku', roomId);
});

document.getElementById('disconnect').addEventListener('click', () => {
    client.disconnect();
});

document.getElementById('send').addEventListener('click', () => {
    const content = document.getElementById('message').value;
    const color = document.getElementById('color').value;
    const size = document.getElementById('size').value;

    client.sendDanmaku(content, null, { color, size });
    document.getElementById('message').value = '';
});

document.getElementById('message').addEventListener('keypress', (e) => {
    if (e.key === 'Enter') {
        document.getElementById('send').click();
    }
});